package com.knight.security.browser;

import com.knight.security.browser.authentication.KnightAuthenticationFailureHandle;
import com.knight.security.browser.authentication.KnightAuthenticationSuccessHandle;
import com.knight.security.core.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 浏览器安全验证配置
 *
 * @author knight
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private KnightAuthenticationSuccessHandle authenticationSuccessHandle;
    @Autowired
    private KnightAuthenticationFailureHandle authenticationFailureHandle;
    /**
     * 配置密码加密方式
     *
     * @return
     */
    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //设置表单登陆
                .loginPage("/authentication/require") //设置登陆页面
/*                .usernameParameter("customUserName")
                .passwordParameter("customPassword")*/
                .loginProcessingUrl("/authentication/form") //设置登陆调用的接口
                .successHandler(authenticationSuccessHandle)// 登录成功处理器
                .failureHandler(authenticationFailureHandle) //登录失败处理器
                .and()
                .authorizeRequests() //配置需要认证的请求
                .antMatchers("/authentication/require", securityProperties.getBrowser().getLoginPage())
                .permitAll() //配置链接无需进行权限校验
                .anyRequest() //任何请求
                .authenticated() //都需要进行认证
                .and()
                .csrf().disable(); // 失效CSRF
    }
}
